/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Lib;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author scriptoff
 */
public class Transport implements TransportInterface {

    private Socket s = null;
    private ObjectInputStream oIS = null;
    private ObjectOutputStream oOS = null;

    public Transport() {
    }

    public void connecter(String host, int port) throws ErreurConnectionException {
        try {
            setHostPort(host, port);
        } catch (UnknownHostException ex) {
            throw new ErreurConnectionException();
        } catch (IOException ex) {
            throw new ErreurConnectionException();
        }
    }
    
    private void setHostPort(String host, int port) throws UnknownHostException, IOException {
        Socket so = new Socket(host, port);
        setSocket(so);
    }

    public void setSocket(Socket s) throws IOException {
        this.s = s;
        creerNiveauObjet();
    }

    private void creerNiveauObjet() throws IOException {
        oOS = new ObjectOutputStream(s.getOutputStream());
        oIS = new ObjectInputStream(s.getInputStream());
    }

    public Object recevoir() throws ErreurReceptionException {
        try {
            return oIS.readObject();
        } catch (IOException ex) {
            throw new ErreurReceptionException();
        } catch (ClassNotFoundException ex) {
            throw new ErreurReceptionException();
        }
    }

    public void envoyer(Object o) throws ErreurEnvoiException {
        try {
            oOS.writeObject(o);
        } catch (IOException ex) {
            throw new ErreurEnvoiException();
        }
    }

    public void fermer() throws ErreurFermetureException {
        if (s != null) {
            try {
                s.close();
            } catch (IOException ex) {
                throw new ErreurFermetureException();
            }
        }
    }
}
